package net.flintx.array;

import java.util.Arrays;

/**
 * Created by flintx on 2018/1/4.
 */
public class RemoveDuplicatesFromSortedArray {

    public int removeDuplicates(int[] nums) {
        /** 
         * removeDuplicates
         *
         * @Description:
         *  Given a sorted array, remove the duplicates in-place such that each element appear only once and return the new length.
         *  Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
         * @Example:
         *  Given nums = [1,1,2]
         *  Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
         *  It doesn't matter what you leave beyond the new length.
         * @Params: [nums] 
         * @Return: int 
         * @Date: 2018/1/4 
         */
        int len = nums.length;
        if (len <= 1) {
            return len;
        }
        int cnt = 0;
        for (int i = 1; i < nums.length; ) {
            int pos = i - 1;
            while (i < nums.length && nums[pos] == nums[i]) {
                len -= 1;
                i += 1;
            }
            if (i == nums.length) {
                continue;
            }
            cnt += 1;
            nums[cnt] = nums[i];
            i += 1;
        }
        return len;
    }

    /**
     * @param nums
     * @return
     */
    public int betterMethod(int[] nums) {
        int i = nums.length > 0? 1 : 0;
        for (int num: nums) {
            if (num != nums[i - 1]) {
                nums[i++] = num;
            }
        }
        return i;
    }
    public static void main(String[] args) {
//        int[] nums = {1, 1, 2, 2, 2, 2, 2, 3, 4, 5};
        int[] nums = {1, 1, 1};
        System.out.println(new RemoveDuplicatesFromSortedArray().removeDuplicates(nums));
    }
}
